package com.wdh.kjs.activity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.Adapter.InvestmentDetailFourAdapter;
import com.wdh.kjs.R;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.util.DateUtilChange;
import com.wdh.kjs.util.DateUtils;
import com.wdh.kjs.util.ToastUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by feifei on 2016/6/23.
 */
public class investrecordActivity extends BaseTopActivity {
    private PullToRefreshListView investrecordlist1;
    private JsonModel jsonModel;
    private List<HashMap<String, String>> datas;
    private String itemId;
    private InvestmentDetailFourAdapter investmentDetailAdapter;
    public static int page ;
    public static int rows =10 ;
    public static int totalrecords = 0;
    public static boolean mLoading = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.investrecord);
        itemId = getIntent().getStringExtra("itemId");
        investrecordlist1 = (PullToRefreshListView) findViewById(R.id.investrecordlist1);
        initweb();
    }

    private void initweb() {
        page=1;
        RequestParams params = new RequestParams();

        params.addBodyParameter("itemId", itemId);
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("rows", rows + "");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_Invest_DETAIL, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);

                if (jsonModel.success) {
                    totalrecords = jsonModel.getTotalrecords();
                    item();
                }


            }

            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(investrecordActivity.this, "网络异常！");
            }
        });

    }

    private void item() {
        investmentDetailAdapter=new InvestmentDetailFourAdapter(this,initListViewData());
        investrecordlist1.setAdapter(investmentDetailAdapter);

        investrecordlist1.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        investrecordlist1.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

            // 下拉Pulling Down
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 下拉的时候数据重置
            }

            // 上拉Pulling Up
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 上拉的时候添加选项

                String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);


                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                new GetDataTask().execute();


            }

        });
    }
    private class GetDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (totalrecords > datas.size()) {

                page += 1;
                try {
                    getMoreList();

                } catch (Exception e) {
                    page -= 1;
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            if (mLoading == false)
                ToastUtils.showShort(investrecordActivity.this, "已无更多数据！");
            investrecordlist1.onRefreshComplete();

            super.onPostExecute(aVoid);

        }
    }

    private void getMoreList() {
        RequestParams params = new RequestParams();

        params.addBodyParameter("itemId", itemId);
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("rows", rows + "");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_Invest_DETAIL, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);

                if (jsonModel.success) {
                    totalrecords = jsonModel.getTotalrecords();
                    more();
                }


            }

            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(investrecordActivity.this, "网络异常！");
            }
        });

    }

    private void more() {
        for(int i=0;i<jsonModel.getInvestUsers().size();i++){
            HashMap<String, String> hashMap = new HashMap<>();
            BigDecimal mybigDecimal =new BigDecimal(jsonModel.getInvestUsers().get(i).getTotalInvestment()+"").setScale(2, RoundingMode.HALF_UP);
            hashMap.put("tv_item_id_four_phone", jsonModel.getInvestUsers().get(i).getNickName());
            hashMap.put("tv_item_id_four_money", "￥"+mybigDecimal);
            String time = DateUtilChange.timestamp2String(jsonModel.getInvestUsers().get(i).getCreatedStamp(), DateUtilChange.DEFAULT_SECOND_FORMAT);
            hashMap.put("tv_item_id_four_time", time);
            datas.add(hashMap);
        }
        if (datas.size() == totalrecords)
            mLoading = false;
        investmentDetailAdapter.notifyDataSetChanged();
    }

    private List<HashMap<String,String>> initListViewData() {
        datas = new ArrayList<>();
        for(int i=0;i<jsonModel.getInvestUsers().size();i++){
            HashMap<String, String> hashMap = new HashMap<>();
            BigDecimal mybigDecimal =new BigDecimal(jsonModel.getInvestUsers().get(i).getTotalInvestment()+"").setScale(2, RoundingMode.HALF_UP);
            hashMap.put("tv_item_id_four_phone", jsonModel.getInvestUsers().get(i).getNickName());
            hashMap.put("tv_item_id_four_money", "￥"+mybigDecimal);
            String time = DateUtilChange.timestamp2String(jsonModel.getInvestUsers().get(i).getCreatedStamp(), DateUtilChange.DEFAULT_SECOND_FORMAT);
            hashMap.put("tv_item_id_four_time", time);
            datas.add(hashMap);
        }
        return datas;

    }
}
